import DataStandard from '@/services/data-factory/index';
import {
  ActionType,
  FooterToolbar,
  PageContainer,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProTable,
} from '@ant-design/pro-components';
import type { PopconfirmProps } from 'antd';
import { Button, Divider, Drawer, message, Modal, Popconfirm } from 'antd';
import React, { useRef, useState } from 'react';
import CreateForm from './CreateForm';
import EnumDetail from './EnumDetail';
import StandardDetail from './StandardDetail';
import UpdateForm from './UpdateForm';

const {
  getDataStandardListUsingPost,
  changeStatusUsingPut,
  deleteStandardUsingDelete,
  // getEnumRangeUsingGet,
  uploadCodeTableUsingPost1,
} = DataStandard.dataStandardsguanlikongzhiqi;
const { getCodeTableDetailUsingGet } = DataStandard.codeTableguanlikongzhiqi;
//分页类型
interface paginationType {
  pageSizeOptions: string[];
  showSizeChanger: boolean;
  total: number;
  current: number;
  pageSize: number;
}

const cancel: PopconfirmProps['onCancel'] = (e) => {
  console.log(e);
  message.error('操作取消');
};

/**
 * 添加节点
 * @param fields
 */

/**
 * 更新节点
 * @param fields
 */

/**
 *  删除节点
 * @param selectedRows
 */

const StandardCatalog: React.FC<unknown> = () => {
  const [standardId, setStandardId] = useState<number>();
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] =
    useState<boolean>(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const actionRef = useRef<ActionType>();
  const [row, setRow] = useState<API.UserInfo>();
  const [selectedRowsState, setSelectedRows] = useState<
    dataFactory.QueryCodeTableDTO_[]
  >([]);
  const [pagination, setPagination] = useState<paginationType>({
    pageSizeOptions: ['10', '20', '30'],
    showSizeChanger: true,
    current: 1,
    pageSize: 20,
    total: 0,
  });
  // 获取标准列表
  const [data, setData] = useState([]);
  const getDataStandardList = async (params = {}) => {
    const { data, code, msg } = await getDataStandardListUsingPost({
      ...params, // 传递分页、过滤等参数
      pageNumber: pagination.current,
      pageSize: pagination.pageSize,
    });
    console.log(data);
    if (code === 100200) {
      setData(data.records || []); // 更新表格数据
      setPagination((prevPagination) => ({
        ...prevPagination,
        total: data.totalItems, // 更新总条数
      }));
    }
    return {
      data: data || [], // 返回查询到的数据
      code,
      message: msg, // 使用解构出来的 msg
    };
  };
  // 修改状态
  const updataeStatues = async (
    standardIdList: number[],
    standardStatus: { [key: string]: any } | undefined,
  ) => {
    await changeStatusUsingPut({
      standardIdList: standardIdList,
      standardStatus: standardStatus,
    });
    // debugger;
    console.log(standardIdList, standardStatus);

    message.success('状态修改成功');
    getDataStandardList();
  };
  // 删除码表
  const handleDelete = async (standardId: number) => {
    await deleteStandardUsingDelete({ standardId });
    message.success('删除成功');
    getDataStandardList();
  };
  // 点击标准编号，获取详情
  //// 点击标准编号 详情
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [enumDetailModalVisible, setEnumDetailModalVisible] = useState(false);

  // 点击码表编号 详情
  const [detailData, setDetailData] = useState<any[]>([]);
  const [enumDetailData, setEnumDetailData] = useState<any[]>([]);
  // 新增状态保存当前码表编号
  const [standardNumber, setStandardNumber] = useState<string | undefined>(
    undefined,
  );
  const [enumStandardNumber, setEnumStandardNumber] = useState<
    string | undefined
  >(undefined);

  // 获取枚举范围
  const handleEnum = async (record) => {
    // 打开弹框并显示 record 的信息
    try {
      const codeTableId = record.enumerationRange;
      console.log(codeTableId);
      // 调用接口获取码表详细信息
      const res = await getCodeTableDetailUsingGet({
        codeTableId,
      });
      console.log(res);
      // 确保从 res.data 中提取 codeTableSetting
      const codeTableSetting = res.data?.codeTableSetting || [];
      // 合并数据并设置状态
      setEnumDetailData(codeTableSetting);
      console.log(codeTableSetting);
      const codeTableNumber = res.data?.codeTableNumber;
      setEnumDetailModalVisible(true);
      setEnumStandardNumber(codeTableNumber); // 传递标准编号到弹窗
    } catch (error) {
      message.error('无法加载枚举范围信息');
    }
  };
  const DISPLAY_FIELDS = [
    'standardNumber', // 标准编号
    'chineseName', // 中文名称
    'englishName', // 英文名称
    'standardDescription', // 标准说明
    'sourceOrganization', // 来源机构
    'dataType', // 数据类型
    'enumerationRange', // 枚举范围
    'defaultValue', // 默认值
  ];
  const handleRowClick = (record) => {
    // 设置标题字段
    setStandardNumber(record.standardNumber || '');
    // 将原始数据转换为字段名-值的纵向结构
    const fieldMapping = {
      standardNumber: '标准编号',
      chineseName: '中文名称',
      englishName: '英文名称',
      standardDescription: '标准说明',
      sourceOrganization: '来源机构',
      dataType: '数据类型',
      enumerationRange: '枚举范围',
      defaultValue: '默认值',
    };

    // 过滤无关字段并生成纵向数据
    const formattedData = Object.entries(record)
      .filter(([key]) => DISPLAY_FIELDS.includes(key)) //  仅保留白名单字段
      .map(([key, value]) => ({
        fieldName: fieldMapping[key],
        fieldValue: value || '无',
      }));
    setDetailData(formattedData);
    setDetailModalVisible(true);
    setStepFormValues(record);

    // 显式设置弹窗可见状态
    setDetailModalVisible(true);
  };

  // 在组件内部声明 ref 和状态
  const fileInputRef = useRef<HTMLInputElement | null>(null);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);

  // 文件上传逻辑
  const uploadFile = async (file: File) => {
    try {
      const response = await uploadCodeTableUsingPost1({}, file);
      if (response?.code === 100200) {
        message.success('导入成功！');
        getDataStandardList();
      } else {
        message.error(`导入失败：${response?.msg || '未知错误'}`);
      }
    } catch (error) {
      message.error(`上传错误：${error?.message || '网络错误'}`);
    }
  };
  const handleFileChange = (e) => {
    const file = e.target.files?.[0];
    if (file) {
      setSelectedFile(file);
      console.log(selectedFile);

      uploadFile(file); //  立即上传文件
    }
  };
  // 导入按钮点击事件
  const handleImport = () => {
    if (!fileInputRef.current) return;
    fileInputRef.current.click();
  };
  const columns: ProDescriptionsItemProps<any>[] = [
    {
      title: '标准编号',
      dataIndex: 'standardNumber',
      hideInForm: true,
      width: 80,
      render: (text, record) => (
        <a
          href="#"
          onClick={(e) => {
            e.preventDefault(); // 阻止默认跳转
            handleRowClick(record); // 触发弹窗
          }}
        >
          {text}
        </a>
      ),
    },

    {
      title: '中文名称',
      dataIndex: 'chineseName',
      valueType: 'text',
      width: 80,
      // hideInForm: true,
      formItemProps: {
        // hidden: true,
        rules: [
          {
            required: true,
            message: '中文名称为必填项',
          },
        ],
      },
    },
    {
      title: '英文名称',
      dataIndex: 'englishName',
      // hideInForm: true,
      width: 80,
      formItemProps: {
        // hidden: true,
        rules: [
          {
            required: true,
            message: '英文名称为必填项',
          },
        ],
      },
    },
    {
      title: '标准说明',
      dataIndex: 'standardDescription',
      hideInSearch: true,
      width: 80,
    },
    {
      title: '来源机构',
      dataIndex: 'sourceOrganization',
      // hideInForm: true,

      valueEnum: {
        0: { text: '数宜信', status: 'shu' },
        1: { text: '8520', status: '8520' },
      },
      formItemProps: {
        // hidden: true,
        rules: [
          {
            required: true,
            message: '来源机构为必填项',
          },
        ],
      },
    },
    {
      title: '数据类型',
      dataIndex: 'dataType',
      hideInSearch: true,
      valueEnum: {
        0: { text: 'Int', status: 'Int' },
        1: { text: 'Float', status: 'Float' },
        2: { text: 'Enum', status: 'Enum' },
        3: { text: 'String', status: 'String' },
      },
      formItemProps: {
        // hidden: true,
        rules: [
          {
            required: true,
            message: '数据类型为必填项',
          },
        ],
      },
    },
    {
      title: '数据长度',
      dataIndex: 'dataLength',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '数据精度',
      dataIndex: 'dataAccuracy',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '默认值',
      dataIndex: 'defaultValue',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '取值范围',
      // dataIndex: `${valueRangeMin}-${valueRangeMax}`,
      dataIndex: 'valueRange',
      hideInSearch: true,
      hideInForm: true,
      render: (_, record) => {
        if (record.valueRangeMin === null && record.valueRangeMax === null) {
          return '-'; // 如果 valueRangeMin 和 valueRangeMax 都为空，返回 null
        }
        return `${record.valueRangeMin}-${record.valueRangeMax}`;
      },
    },
    {
      title: '枚举范围',
      dataIndex: 'enumerationRange',
      hideInSearch: true,
      hideInForm: true,
      render: (text, record) => (
        <a
          href="#"
          onClick={(e) => {
            e.preventDefault(); // 阻止默认跳转
            handleEnum(record); // 触发弹窗
          }}
        >
          {text}
        </a>
      ),
    },
    {
      title: '是否可为空',
      dataIndex: 'whetherEmpty',
      hideInSearch: true,
      // hideInForm: true,
      valueEnum: {
        0: { text: '不可为空', status: 0 },
        1: { text: '可为空', status: 1 },
      },
      formItemProps: {
        // hidden: true,
        rules: [
          {
            required: true,
            message: '是否为空为必填项',
          },
        ],
      },
    },
    {
      title: '标准状态',
      dataIndex: 'standardStatus',
      // hideInTable: true,
      hideInForm: true,
      // hideInSearch: true,
      valueEnum: {
        0: { text: '未发布', status: 0 },
        1: { text: '已发布', status: 1 },
        2: { text: '已停用', status: 2 },
      },
    },
    {
      title: '更新日期',
      dataIndex: 'updateTime',
      hideInSearch: true,
      hideInForm: true,
      width: 148,
    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 244,
      render: (_, record) => (
        <>
          <Popconfirm
            title="状态确认"
            description="你确定要修改状态吗？"
            onConfirm={() =>
              updataeStatues(
                [record.standardId],
                record.standardStatus === 0 ? 1 : 0,
              )
            }
            onCancel={cancel}
            okText="确认"
            cancelText="取消"
          >
            {/* {standardStatus ? '发布' : '停用'} */}
            <Button title="primary">
              {record.standardStatus === 0 ? '发布' : '停用'}
            </Button>
          </Popconfirm>
          <Divider type="vertical" />
          <Button
            type="primary"
            onClick={() => {
              setStandardId(record.standardId);
              handleModalVisible(true);
              setStepFormValues(record);
            }}
            disabled={record.standardStatus === 1}
          >
            编辑
          </Button>
          <Divider type="vertical" />
          <Popconfirm
            title="删除确认"
            description="你确定要删除吗？"
            onConfirm={() => {
              handleDelete(record.standardId);
            }}
            onCancel={cancel}
            okText="确认"
            cancelText="取消"
          >
            <Button danger>删除</Button>
          </Popconfirm>
          ,
        </>
      ),
    },
  ];
  // 检查是否全部选择未发布的数据
  const allSelectedUnpublished = selectedRowsState.every(
    (row) => row.standardStatus === 0,
  );
  // 检查是否全部选择已发布的数据
  const allSelectedPublished = selectedRowsState.every(
    (row) => row.standardStatus === 1,
  );
  return (
    <PageContainer
      header={{
        title: '数据标准管理',
      }}
    >
      <input
        ref={fileInputRef}
        type="file"
        onChange={handleFileChange}
        style={{ display: 'none' }}
      />
      <ProTable<API.UserInfo>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="standardId"
        search={{
          labelWidth: 70,
        }}
        toolBarRender={() => [
          <Button
            key="1"
            type="primary"
            onClick={() => {
              handleModalVisible(true); // 打开新增模态框
              setStepFormValues({}); // 清空初始值
              setStandardId(undefined);
            }}
          >
            新建
          </Button>,
          <Button
            key="2"
            type="primary"
            onClick={() => {
              handleImport();
            }}
          >
            标准导入
          </Button>,
        ]}
        request={getDataStandardList}
        columns={columns}
        pagination={{
          ...pagination,
          onChange: (page, pageSize) => {
            setPagination({
              ...pagination,
              current: page,
              pageSize: pageSize || pagination.pageSize,
            });
          },
        }}
        dataSource={data}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              项&nbsp;&nbsp;
            </div>
          }
        >
          <Button
            type="primary"
            onClick={async () => {
              await updataeStatues(
                selectedRowsState.map((row) => row.standardId),
                1,
              );
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
            disabled={!allSelectedUnpublished} // 禁用条件：没有选择数据或选择的不是未发布的数据
          >
            批量发布
          </Button>
          <Button
            type="primary"
            onClick={async () => {
              await updataeStatues(
                selectedRowsState.map((row) => row.standardId),
                2,
              );
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
            disabled={!allSelectedPublished} // 禁用条件：没有选择数据或选择的不是已发布的数据
          >
            批量停用
          </Button>
        </FooterToolbar>
      )}
      <CreateForm
        onCancel={() => {
          handleModalVisible(false);
          setStandardId(undefined);
          setStepFormValues({});
        }}
        modalVisible={createModalVisible}
        onSuccess={async () => {
          // 新增成功回调
          handleModalVisible(false);
          getDataStandardList(); // 调用父组件传递的 getCodeTableList 方法
          setStandardId(undefined); // 成功提交后也需重置

          // initialValues = { stepFormValues }; // 传递 stepFormValues 作为 initialValues
          // standardId = { standardId }; // 传递 standardId
        }}
        getDataStandardList={getDataStandardList}
        initialValues={stepFormValues} // 传递 stepFormValues 作为 initialValues
        standardId={standardId} // 传递 codeTableId
      >
        <ProTable<API.UserInfo, API.UserInfo>
          onSubmit={async (value) => {
            const success = await handleAdd(value);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          type="form"
          columns={columns}
        />
      </CreateForm>
      {stepFormValues && Object.keys(stepFormValues).length ? (
        <UpdateForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleUpdateModalVisible(false);
              setStepFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setStepFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={stepFormValues}
        />
      ) : null}

      <Drawer
        width={600}
        open={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.name && (
          <ProDescriptions<API.UserInfo>
            column={2}
            title={row?.name}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.name,
            }}
            columns={columns}
          />
        )}
      </Drawer>
      <Modal
        title={standardNumber}
        visible={detailModalVisible}
        onCancel={() => {
          setDetailModalVisible(false);
          setStandardNumber(undefined);
          setDetailData([]); // 重置为空数组
        }}
        style={{ width: 600, backgroundColor: '#fff' }}
      >
        {detailData.length > 0 ? (
          <StandardDetail dataSource={detailData} />
        ) : (
          <div style={{ padding: 20 }}>加载中...</div>
        )}
      </Modal>
      <Modal
        title={enumStandardNumber}
        visible={enumDetailModalVisible}
        onCancel={() => {
          setEnumDetailModalVisible(false);
          setEnumStandardNumber(undefined);
          setEnumDetailData([]); // 重置为空数组
        }}
        style={{ width: 600, backgroundColor: '#fff' }}
      >
        {enumDetailData.length > 0 ? (
          <EnumDetail dataSource={{ codeTableSetting: enumDetailData }} />
        ) : (
          <div style={{ padding: 20 }}>加载中...</div>
        )}
      </Modal>
    </PageContainer>
  );
};

export default StandardCatalog;
